const http = require('http');
const sqlite3 = require('../app/backend/node_modules/sqlite3').verbose();
const db = new sqlite3.Database('../app/backend/data/pph.sqlite');

console.log('🚀 重算所有受影响物料的目标值/预估值/达成率...');
console.log('=====================================');

async function getAffectedMaterials() {
  return new Promise((resolve, reject) => {
    // 获取所有有节拍数据的物料（这些都可能受到之前错误逻辑的影响）
    db.all(`SELECT DISTINCT material_code 
            FROM pph_records 
            WHERE (target_takt_time IS NOT NULL OR target_motor_takt_time IS NOT NULL)
            AND record_date >= '2025-09-01'
            ORDER BY material_code`, (err, materials) => {
      if (err) {
        console.error('❌ 获取物料列表失败:', err);
        return reject(err);
      }
      
      const materialCodes = materials.map(m => m.material_code);
      console.log(`📋 发现 ${materialCodes.length} 个物料需要重算:`);
      
      // 分批显示物料列表
      const batchSize = 20;
      for (let i = 0; i < materialCodes.length; i += batchSize) {
        const batch = materialCodes.slice(i, i + batchSize);
        console.log(`批次 ${Math.floor(i / batchSize) + 1}: ${batch.join(', ')}`);
      }
      
      db.close();
      resolve(materialCodes);
    });
  });
}

async function startRecomputeJob(materialCodes, batchSize = 50) {
  // 分批处理，避免单次请求过大
  const batches = [];
  for (let i = 0; i < materialCodes.length; i += batchSize) {
    batches.push(materialCodes.slice(i, i + batchSize));
  }
  
  console.log(`\n🔄 将分 ${batches.length} 批次执行重算，每批 ${batchSize} 个物料`);
  
  const results = [];
  
  for (let batchIndex = 0; batchIndex < batches.length; batchIndex++) {
    const batch = batches[batchIndex];
    console.log(`\n📦 执行第 ${batchIndex + 1}/${batches.length} 批次重算...`);
    console.log(`物料: ${batch.join(', ')}`);
    
    try {
      const result = await submitRecomputeRequest(batch, batchIndex + 1);
      results.push(result);
      
      // 批次间延迟，避免服务器压力过大
      if (batchIndex < batches.length - 1) {
        console.log('⏳ 等待 3 秒后执行下一批次...');
        await new Promise(resolve => setTimeout(resolve, 3000));
      }
    } catch (error) {
      console.error(`❌ 第 ${batchIndex + 1} 批次失败:`, error.message);
      results.push({ batch: batchIndex + 1, error: error.message });
    }
  }
  
  return results;
}

function submitRecomputeRequest(materialCodes, batchNumber) {
  return new Promise((resolve, reject) => {
    const data = JSON.stringify({
      material_codes: materialCodes,
      from_date: '2025-09-01',
      to_date: '2025-09-21',
      recalc_pph: false,
      batch_info: `批次${batchNumber}`
    });

    const options = {
      hostname: '127.0.0.1',
      port: 3011,
      path: '/api/recompute/jobs/start',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
      }
    };

    const req = http.request(options, (res) => {
      let responseData = '';
      
      res.on('data', (chunk) => {
        responseData += chunk;
      });
      
      res.on('end', () => {
        try {
          const result = JSON.parse(responseData);
          console.log(`✅ 批次${batchNumber}提交成功:`);
          console.log(`- 任务ID: ${result.jobId || result.id}`);
          console.log(`- 状态: ${result.status || result.message}`);
          
          resolve({
            batch: batchNumber,
            jobId: result.jobId || result.id,
            status: result.status || result.message,
            materialCount: materialCodes.length,
            materials: materialCodes
          });
        } catch (e) {
          console.log(`📋 批次${batchNumber}服务器响应:`, responseData);
          resolve({
            batch: batchNumber,
            response: responseData,
            materialCount: materialCodes.length
          });
        }
      });
    });

    req.on('error', (e) => {
      reject(new Error(`批次${batchNumber}请求失败: ${e.message}`));
    });

    req.write(data);
    req.end();
  });
}

// 主执行流程
async function main() {
  try {
    console.log('🔍 步骤1: 获取需要重算的物料列表...');
    const materialCodes = await getAffectedMaterials();
    
    if (materialCodes.length === 0) {
      console.log('✅ 没有需要重算的物料');
      return;
    }
    
    console.log('\n🚀 步骤2: 开始分批重算...');
    const results = await startRecomputeJob(materialCodes, 30); // 每批30个物料
    
    console.log('\n📊 重算任务提交总结:');
    console.log(`- 总物料数: ${materialCodes.length} 个`);
    console.log(`- 提交批次: ${results.length} 批`);
    
    const successfulBatches = results.filter(r => r.jobId);
    const failedBatches = results.filter(r => r.error);
    
    console.log(`- 成功批次: ${successfulBatches.length} 批`);
    console.log(`- 失败批次: ${failedBatches.length} 批`);
    
    if (successfulBatches.length > 0) {
      console.log('\n✅ 成功提交的任务:');
      successfulBatches.forEach(result => {
        console.log(`  批次${result.batch}: 任务ID ${result.jobId} (${result.materialCount}个物料)`);
      });
      
      console.log('\n📊 监控任务进度:');
      console.log('可以通过以下方式查看任务状态:');
      console.log('1. 访问 http://127.0.0.1:3011/admin/recompute 查看任务列表');
      console.log('2. 或使用API查询具体任务状态');
    }
    
    if (failedBatches.length > 0) {
      console.log('\n❌ 失败的批次:');
      failedBatches.forEach(result => {
        console.log(`  批次${result.batch}: ${result.error}`);
      });
    }
    
  } catch (error) {
    console.error('❌ 执行失败:', error);
    process.exit(1);
  }
}

// 执行主流程
main();
